package com.qf.commons.mysql.webintercepter;

import com.qf.commons.mysql.utils.QphonePage;
import com.qf.data.page.Page;
import com.qf.data.r.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * description: 基于SpringMVC的响应体处理器 - 处理返回的R对象，统一设置分页信息
 * author: Ken
 * 公众号：Java架构栈
 */
@Slf4j
@RestControllerAdvice
public class PageResponseBodyAdvice implements ResponseBodyAdvice<R> {

    /**
     * 条件判断方法，判断什么情况下，会触发beforeBodyWrite方法
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //判断一下拦截方法的返回类型
        return returnType.getMethod().getReturnType() == R.class;
    }

    @Override
    public R beforeBodyWrite(R body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //获取ThreadLocal中的Page对象
        Page page = QphonePage.getPage();
        if (page == null) return body;

        log.debug("[page responseadvice] 分页返回值处理器生效！ {}", page);
        //将分页信息，设置到R对象中，一起返回给客户端
        body.setPage(page);
        return body;
    }
}
